const { ENV, BASE_URLS } = require('./config');

// 环境判断
const isDev = __wxConfig.envVersion === 'develop';

// 获取当前环境的BASE_URL
const BASE_URL = BASE_URLS[isDev ? ENV.DEV : ENV.PROD];

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加基础URL，处理斜杠重复问题
  const baseUrl = BASE_URL.endsWith('/') ? BASE_URL.slice(0, -1) : BASE_URL;
  const url = config.url.startsWith('/') ? config.url : `/${config.url}`;
  config.url = `${baseUrl}${url}`;
  
  // 获取token
  const token = wx.getStorageSync('token');
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  if (statusCode >= 200 && statusCode < 300) {
    return data;
  }
  // 处理错误
  wx.showToast({
    title: data.message || '请求失败',
    icon: 'none'
  });
  return Promise.reject(data);
};

// 基础请求方法
const request = (options) => {
  const config = requestInterceptor(options);
  return new Promise((resolve, reject) => {
    wx.request({
      ...config,
      success: (res) => {
        resolve(responseInterceptor(res));
      },
      fail: (error) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        reject(error);
      }
    });
  });
};

// RESTful API 方法
const api = {
  // GET 请求
  get: (url, params = {}) => {
    return request({
      url,
      method: 'GET',
      data: params
    });
  },

  // POST 请求
  post: (url, data = {}) => {
    return request({
      url,
      method: 'POST',
      data
    });
  },

  // PUT 请求
  put: (url, data = {}) => {
    return request({
      url,
      method: 'PUT',
      data
    });
  },

  // DELETE 请求
  delete: (url, data = {}) => {
    return request({
      url,
      method: 'DELETE',
      data
    });
  },

  // PATCH 请求
  patch: (url, data = {}) => {
    return request({
      url,
      method: 'PATCH',
      data
    });
  }
};

// 导出API实例
module.exports = {
  api,
  request
};
